package com.th.cash.th2.login

import android.R.attr.data
import android.graphics.Color
import android.provider.ContactsContract
import android.view.View
import androidx.activity.viewModels
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.th.basemodel.base.BaseVB2Activity2
import com.th.basemodel.base.BaseViewModel
import com.th.basemodel.ext.gotoActivity
import com.th.basemodel.ext.toast
import com.th.cash.databinding.ActivityLoginBinding
import com.th.resmodel.R
import com.th.cash.th2.main.MainActivity
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicInteger
import androidx.core.view.isVisible
import com.th.basemodel.ext.unLine
import com.th.basemodel.utils.KeyboardUtils
import com.th.cash.util.ActivityRouter
import com.th.cash.util.Constants

//登陆页
class LoginActivity : BaseVB2Activity2<ActivityLoginBinding>() {

    private val mViewModel by viewModels<LoginVm>()
    private var countdownJob: Job? = null

    private var mPhone = ""

    override fun getVm(): BaseViewModel {
        return mViewModel
    }

    override fun setWindowPadding() {
        ViewCompat.setOnApplyWindowInsetsListener(mBinding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            insets
        }
    }

    override fun observeViewModel() {
        lifecycleScope.launch {
            mViewModel.uiState.collect {
                when (it) {
                    is LoginState.SendSmsSuccess -> {
                        it.response?.let { value ->
                            // 1. Update visibility
                            mBinding.clPhone.visibility = View.GONE
                            mBinding.clCode.visibility = View.VISIBLE

//                            KeyboardUtils.forceShowKeyboard(this@LoginActivity)

                            mPhone = value.phone

                            mBinding.tvCodePhone.text = "+66${mPhone}"

                            // 2. Start countdown
                            val countdownValue =
                                value.MRZamUjLamppostNaUomFq.YUnUGagRaylessPEqOiFS.toIntOrNull()
                                    ?: 0
                            startCountdown(countdownValue)

                            mBinding.codeView.showKeyBoard()
                        }
                    }

                    is LoginState.VerifyResult -> {
                        if (it.isSuccess) {
                            gotoActivity<MainActivity>()
                            finish()
                        } else {
                            mBinding.codeView.clearCode()
                        }
                    }

                    else -> {}
                }
            }
        }
    }

    private fun startCountdown(initialValue: Int) {
        // Cancel any existing countdown
        countdownJob?.cancel()

        val count = AtomicInteger(initialValue)
        countdownJob = lifecycleScope.launch {
            // Set initial state
            mBinding.tvCodeReSend.isEnabled = false
            mBinding.tvCodeReSend.setBackgroundResource(R.drawable.bg_code_resend_disabled)
            mBinding.tvCodeReSend.setTextColor(Color.parseColor("#0D0D0D"))

            while (count.get() > 0) {
                mBinding.tvCodeReSend.text = count.get().toString() + "s"
                delay(1000) // 1 second delay
                count.decrementAndGet()
            }

            // Set final state
            mBinding.tvCodeReSend.isEnabled = true
            mBinding.tvCodeReSend.setBackgroundResource(R.drawable.bg_code_resend_enabled)
            mBinding.tvCodeReSend.setTextColor(Color.parseColor("#FFFFFF"))
            mBinding.tvCodeReSend.text = "ส่งอีกครั้ง"
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        countdownJob?.cancel()
    }

    override fun init() {
        initTitle()
        setupPhoneInputListener()
        setupSubmitButton()
        setupReSendButton()
        setupVerificationCodeListener()
        setBackButton()
        setPrivacyButton()
//        mBinding.tvPhonePrivacy.unLine()
    }

    private fun setPrivacyButton() {
        mBinding.tvPhonePrivacy.setOnClickListener {
            ActivityRouter.next(
                this,
                Constants.getPrivy()
            )
        }
    }

    private fun initTitle() {
        mBinding.header.headTitle.text = "เข้าสู่ระบบ"
    }

    private fun setBackButton() {
        mBinding.header.headBack.setOnClickListener {
            if (mBinding.clCode.isVisible) {
                mBinding.codeView.clearCode()
                mBinding.clPhone.visibility = View.VISIBLE
                mBinding.clCode.visibility = View.GONE
//                KeyboardUtils.hideKeyboard(this)
            } else {
                finish()
            }
        }
    }

    private fun setupVerificationCodeListener() {
        mBinding.codeView.setOnCodeCompleteListener { code ->
            val request = LoginRequest(
                mPhone,
                code,
                "duiuyiton"
            )
            mViewModel.intentChannel.trySend(LoginIntent.Login(request))
        }
    }

    private fun setupPhoneInputListener() {
        mBinding.etPhone.addTextChangedListener(object : android.text.TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: android.text.Editable?) {
                val isEnabled = s?.length ?: 0 >= 9
                mBinding.tvPhoneSubmit.isEnabled = isEnabled
                mBinding.tvPhoneSubmit.setBackgroundResource(
                    if (isEnabled) R.drawable.bg_submit_enable
                    else R.drawable.bg_submit_un_enable
                )
            }
        })
    }

    private fun setupSubmitButton() {
        mBinding.tvPhoneSubmit.setOnClickListener {
            if (!mBinding.cbPhoneAgreement.isChecked) {
                toast("กรุณาตรวจสอบข้อตกลงความเป็นส่วนตัวและทำเครื่องหมายยินยอม")
                return@setOnClickListener
            }

            val phoneNumber = mBinding.etPhone.text.toString()
            val request = SendSmsRequest(
                fqNHWPuQuerulouslyXUxeOCr = phoneNumber,
                FqMSRlOMicroscopiumEaMNrgV = "juyttrr" // Assuming this is required but empty for now
            )

            mViewModel.intentChannel.trySend(LoginIntent.SendSms(request))
        }
    }

    private fun setupReSendButton() {
        mBinding.tvCodeReSend.setOnClickListener {
            val phoneNumber = mBinding.etPhone.text.toString()
            val request = SendSmsRequest(
                fqNHWPuQuerulouslyXUxeOCr = phoneNumber,
                FqMSRlOMicroscopiumEaMNrgV = "juyttrr" // Assuming this is required but empty for now
            )

            mViewModel.intentChannel.trySend(LoginIntent.SendSms(request))
        }
    }
}